package com.example.springboot.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * WebFilter方式
 * <p> 注解{@link WebFilter }是Servlet3.0的一个注解，用于标注一个Filter。
 * <p> Spring Boot支持这种方式，只需要在自定义的Filter上标注该注解即可。
 * <p> 不过要想 WebFilter注解生效，需要在配置类上标注另外一个注解 @ServletComponentScan用于扫描使其生效
 * <p> 使用{@link WebFilter#urlPatterns } 配置拦截路径
 * <p>
 * @author Zhang.Z
 * @version 2025-09-20
 */
@Order(2)
@WebFilter(filterName = "corsFilter", urlPatterns = {"/*"})
public class CorsFilter implements Filter {

    /**
     * 对指定url进行鉴权
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        System.out.println("cors filter 请求前 = " + uri);
        if (uri.startsWith("/private")) {
            returnJson(res, "no permission");
            return;
        }

        chain.doFilter(request, response);

        System.out.println("cors filter 请求后 = " + uri);
    }


    /**
     * 自定义返回信息
     */
    private void returnJson(HttpServletResponse response, String msg) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(msg);
            writer.flush();
        } catch (IOException e) {

        }
    }
}
